package org.holynite.fieldmanage.services

import org.holynite.fieldmanage.Utils.ManagementException
import org.holynite.fieldmanage.ejbs.AuthorizationManagement
import org.holynite.fieldmanage.entities.AdministratorRole
import org.holynite.fieldmanage.persistence.AdministratorRoleEAO
import org.holynite.fieldmanage.persistence.RolePrivilegeEAO
import org.holynite.fieldmanage.types.Exceptions
import org.holynite.fieldmanage.types.Privileges

import javax.annotation.Resource
import javax.ejb.EJB
import javax.ejb.Stateless
import javax.transaction.UserTransaction

/**
 * Created by midnite on 15/1/12.
 */
@Stateless(name = "adminRoleControl", mappedName = "adminRoleControl")
class RoleControlBean implements AuthorizationManagement {

	@EJB(beanName = "roleEAO")
	AdministratorRoleEAO roleEao
	@EJB(beanName = "privilegeEAO")
	RolePrivilegeEAO privilegeEao

	@Override
	void addRole(AdministratorRole newRole) throws ManagementException {
		try {
			roleEao.save(newRole)
			newRole.privileges.each { it.belongsTo = newRole.svrid }
			privilegeEao.saveAllPrivilegesInRole(newRole.privileges)
		} catch (Exception e) {
			e.printStackTrace()
			throw new ManagementException(Exceptions.AdministrationRole)
		}
	}

	@Override
	void saveRole(AdministratorRole role) throws ManagementException {
		try {
			privilegeEao.clearOldPrivileges(role.svrid)
			roleEao.update(role)
			role.privileges.each { it.belongsTo = role.svrid }
			privilegeEao.saveAllPrivilegesInRole(role.privileges)
		} catch (Exception e) {
			throw new ManagementException(Exceptions.AdministrationRole)
		}
	}

	@Override
	Boolean removeRole(Object key) throws ManagementException {
		try {
			//todo 检测当前职位是否被使用，如果在使用需要抛出异常
			roleEao.delete(AdministratorRole, key)
			privilegeEao.clearOldPrivileges(key as String)
		} catch (Exception e) {
			false
		}
		true
	}

	@Override
	List<AdministratorRole> listAllDetailedRoles() {
		def roleResult = roleEao.getAllAdministratorRoles()
		def privilegeResult = privilegeEao.allPrivileges
		roleResult.each { r ->
			r.privileges = []
			privilegeResult.each { p ->
				if (p.belongsTo.equals(r.svrid)) r.privileges << p
			}
		}
		roleResult
	}

	@Override
	AdministratorRole fetchRole(String roleId) {
		roleEao.get(AdministratorRole, roleId)
	}

	@Override
	AdministratorRole fillPrivilege(AdministratorRole role) {
		role.privileges = privilegeEao.getAllPrivilegesInRole(role.svrid)
		role
	}

	@Override
	List<AdministratorRole> listAllRoles() {
		roleEao.getAllAdministratorRoles()
	}

	@Override
	Boolean checkRoleHasPrivilege(AdministratorRole role, Privileges privilege) {
		role.privileges.any { it.equals(privilege) }
	}

	@Override
	List<Privileges> getAllPrivileges() {
		Privileges.values()
	}
}
